<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电商平台 - 个人资料</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
        }

        .header {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px 0;
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }

        .nav {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 16px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .nav a:hover {
            background: #f0f0f0;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .welcome {
            color: #666;
        }

        .logout-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .main-content {
            max-width: 800px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .profile-card {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .profile-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            border-bottom: 1px solid #eee;
            padding-bottom: 20px;
        }

        .profile-header h2 {
            color: #333;
            font-size: 24px;
        }

        .edit-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .edit-btn:hover {
            background: #2980b9;
        }

        .save-btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: none;
        }

        .save-btn:hover {
            background: #219653;
        }

        .cancel-btn {
            background: #95a5a6;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: none;
            margin-right: 10px;
        }

        .cancel-btn:hover {
            background: #7f8c8d;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .form-group input:disabled,
        .form-group select:disabled {
            background: #f9f9f9;
            color: #666;
            border-color: #eee;
        }

        .row {
            display: flex;
            gap: 20px;
        }

        .row .form-group {
            flex: 1;
        }

        .footer {
            background: #333;
            color: white;
            text-align: center;
            padding: 20px;
            margin-top: 60px;
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .success-message {
            color: #27ae60;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                gap: 15px;
            }

            .nav {
                flex-wrap: wrap;
                justify-content: center;
            }

            .row {
                flex-direction: column;
                gap: 0;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <div class="header-content">
        <div class="logo">电商平台</div>
        <div class="nav">
            <a href="index.html">首页</a>
            <a href="profile.html">个人资料</a>
            <a href="change-password.html">修改密码</a>
            <div class="user-info">
                <span class="welcome" id="welcomeText">欢迎，用户</span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </div>
    </div>
</div>

<div class="main-content">
    <div class="profile-card">
        <div class="profile-header">
            <h2>个人资料</h2>
            <div>
                <button class="cancel-btn" id="cancelBtn">取消</button>
                <button class="save-btn" id="saveBtn">保存</button>
                <button class="edit-btn" id="editBtn">编辑资料</button>
            </div>
        </div>

        <form id="profileForm">
            <div class="row">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" disabled>
                </div>
                <div class="form-group">
                    <label for="name">姓名</label>
                    <input type="text" id="name" name="name" disabled required>
                    <div class="error-message" id="nameError"></div>
                </div>
            </div>

            <div class="row">
                <div class="form-group">
                    <label for="age">年龄</label>
                    <input type="number" id="age" name="age" min="0" max="150" disabled>
                    <div class="error-message" id="ageError"></div>
                </div>
                <div class="form-group">
                    <label for="sex">性别</label>
                    <select id="sex" name="sex" disabled>
                        <option value="0">女</option>
                        <option value="1">男</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="phone">手机号</label>
                <input type="tel" id="phone" name="phone" pattern="^1[0-9]{10}$" disabled>
                <div class="error-message" id="phoneError"></div>
            </div>

            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" name="email" disabled>
                <div class="error-message" id="emailError"></div>
            </div>

            <div class="success-message" id="successMessage">个人资料更新成功</div>
        </form>
    </div>
</div>

<div class="footer">
    <p>&copy; 2024 电商平台. 保留所有权利.</p>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 检查登录状态
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = 'login.html';
            return;
        }

        // 获取用户信息并填充表单
        loadUserProfile();

        // 设置编辑按钮事件
        document.getElementById('editBtn').addEventListener('click', enableEditing);
        document.getElementById('cancelBtn').addEventListener('click', cancelEditing);
        document.getElementById('saveBtn').addEventListener('click', saveProfile);
    });

    async function loadUserProfile() {
        try {
            const response = await fetch('/api/user/info', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.status === 401) {
                // 登录已过期
                localStorage.removeItem('token');
                window.location.href = 'login.html';
                return;
            }

            const result = await response.json();

            if (result.code === 200) {
                const user = result.data;
                document.getElementById('welcomeText').textContent = `欢迎，${user.name || user.account}`;

                // 填充表单数据
                document.getElementById('username').value = user.account || '';
                document.getElementById('name').value = user.name || '';
                document.getElementById('age').value = user.age || '';
                document.getElementById('sex').value = user.sex || '0';
                document.getElementById('phone').value = user.phone || '';
                document.getElementById('email').value = user.email || '';

                // 如果是管理员，显示管理入口
                if (user.role === 'ADMIN') {
                    const nav = document.querySelector('.nav');
                    const adminLink = document.createElement('a');
                    adminLink.href = 'admin.html';
                    adminLink.textContent = '用户管理';
                    adminLink.style.color = '#e74c3c';
                    nav.insertBefore(adminLink, nav.lastElementChild);
                }
            } else {
                console.error('获取用户信息失败:', result.message);
                alert('获取用户信息失败: ' + result.message);
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            alert('获取用户信息失败，请检查网络连接');
        }
    }

    function enableEditing() {
        // 启用表单字段
        const form = document.getElementById('profileForm');
        const inputs = form.querySelectorAll('input:not(#username), select');
        inputs.forEach(input => {
            input.disabled = false;
        });

        // 显示保存和取消按钮，隐藏编辑按钮
        document.getElementById('editBtn').style.display = 'none';
        document.getElementById('saveBtn').style.display = 'inline-block';
        document.getElementById('cancelBtn').style.display = 'inline-block';
    }

    function cancelEditing() {
        // 禁用表单字段
        const form = document.getElementById('profileForm');
        const inputs = form.querySelectorAll('input, select');
        inputs.forEach(input => {
            input.disabled = true;
        });

        // 隐藏保存和取消按钮，显示编辑按钮
        document.getElementById('editBtn').style.display = 'inline-block';
        document.getElementById('saveBtn').style.display = 'none';
        document.getElementById('cancelBtn').style.display = 'none';

        // 隐藏所有错误消息
        document.querySelectorAll('.error-message').forEach(el => {
            el.style.display = 'none';
        });

        // 重新加载原始数据
        loadUserProfile();
    }

    async function saveProfile() {
        // 验证表单
        const name = document.getElementById('name').value.trim();
        const age = document.getElementById('age').value;
        const phone = document.getElementById('phone').value.trim();
        const email = document.getElementById('email').value.trim();

        // 重置错误消息
        document.querySelectorAll('.error-message').forEach(el => {
            el.style.display = 'none';
        });

        let isValid = true;

        // 验证姓名
        if (!name) {
            document.getElementById('nameError').textContent = '姓名不能为空';
            document.getElementById('nameError').style.display = 'block';
            isValid = false;
        }

        // 验证年龄
        if (age && (age < 0 || age > 150)) {
            document.getElementById('ageError').textContent = '年龄必须在0-150之间';
            document.getElementById('ageError').style.display = 'block';
            isValid = false;
        }

        // 验证手机号
        if (phone && !/^1[0-9]{10}$/.test(phone)) {
            document.getElementById('phoneError').textContent = '手机号格式不正确';
            document.getElementById('phoneError').style.display = 'block';
            isValid = false;
        }

        // 验证邮箱
        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            document.getElementById('emailError').textContent = '邮箱格式不正确';
            document.getElementById('emailError').style.display = 'block';
            isValid = false;
        }

        if (!isValid) {
            return;
        }

        // 准备更新数据（移除了安全问题相关字段）
        const userData = {
            name: name,
            age: age ? parseInt(age) : null,
            sex: parseInt(document.getElementById('sex').value),
            phone: phone || null,
            email: email || null
        };

        try {
            const response = await fetch('/api/user/info', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(userData)
            });

            let result;
            const contentType = response.headers.get('content-type');

            if (contentType && contentType.includes('application/json')) {
                result = await response.json();
            } else {
                const text = await response.text();
                // 尝试从非JSON响应中提取有用信息
                const errorMatch = text.match(/参数校验失败: (.+)/);
                const errorMessage = errorMatch ? errorMatch[1] : text;
                throw new Error(errorMessage);
            }

            if (result.code === 200) {
                // 显示成功消息
                const successMessage = document.getElementById('successMessage');
                successMessage.style.display = 'block';

                // 3秒后隐藏成功消息
                setTimeout(() => {
                    successMessage.style.display = 'none';
                }, 3000);

                // 禁用表单字段
                cancelEditing();
            } else {
                console.error('更新用户信息失败:', result.message);
                alert('更新用户信息失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新用户信息失败:', error);
            // 更友好的错误提示
            let userMessage = '更新用户信息失败';
            if (error.message.includes('Validation failed')) {
                userMessage = '输入数据不合法，请检查表单';
            } else if (error.message.includes('手机号已被其他用户使用')) {
                userMessage = '该手机号已被其他账号使用';
            } else if (error.message.includes('邮箱已被其他用户使用')) {
                userMessage = '该邮箱已被其他账号使用';
            }
            alert(userMessage + ': ' + error.message);
        }
    }

    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('token');
            window.location.href = 'login.html';
        }
    }
</script>
</body>
</html>